<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="班次名称" prop="shiftName">
            <el-input v-model="queryParams.shiftName" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:shift:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:shift:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:shift:remove']"
              >删除</el-button
            >
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:shift:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 370px)"
        v-loading="loading"
        :data="shiftList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="班次名称" align="center" prop="shiftName" />
        <el-table-column label="考勤类型" align="center" prop="attendanceType">
          <template #default="scope">
            <dict-tag :options="attendance_shift_type" :value="scope.row.attendanceType" />
          </template>
        </el-table-column>
        <el-table-column label="考勤时段" align="center" prop="shiftSegments" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['attendance:shift:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['attendance:shift:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改考勤班次对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="shiftFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班次名称" prop="shiftName">
          <el-input v-model="form.shiftName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="考勤时间段" prop="comeLateMinutes" label-width="93px">
          <el-tabs v-model="activeName" @tab-click="handleTabClick" class="demo-tabs" style="width: 100%">
            <el-tab-pane :label="shift.label" :name="shift.attendanceType" v-for="shift of attendanceShifts">
              <template v-for="(segment, index) of form.segments" v-if="activeName === shift.attendanceType">
<!--              <template v-for="(segment, index) of shift.segments" >-->
                <el-row style="padding-bottom: 30px">
                  <el-col :span="8">
                    <el-form-item
                      label="上学时间"
                      :prop="'segments.' + index + '.startTime'"
                      :rules="[
                      { required: true, message: '上学时间不能为空', trigger: 'blur' },
                      { validator: (rule: any, value: string, callback: any) => checkStartTime(rule, value, callback, segment), trigger: 'blur' }
                    ]"
                    >
                      <el-time-picker v-model="segment.startTime" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item>
                      <el-form-item
                        :prop="'segments.' + index + '.signInStart'"
                        :rules="[
                        { required: true, message: '签到开始时间不能为空', trigger: 'blur' },
                        { validator: (rule: any, value: string, callback: any) => checkSignInStart(rule, value, callback, segment), trigger: 'blur' }
                      ]"
                      >
                        <el-time-picker v-model="segment.signInStart" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                        <span style="padding-left: 5px; padding-right: 5px">至</span>
                      </el-form-item>
                      <el-form-item
                        :prop="'segments.' + index + '.signInEnd'"
                        :rules="[
                        { required: true, message: '签到结束时间不能为空', trigger: 'blur' },
                        { validator: (rule: any, value: string, callback: any) => checkSignInEnd(rule, value, callback, segment), trigger: 'blur' }
                      ]"
                      >
                        <el-time-picker v-model="segment.signInEnd" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                        <span style="padding-left: 5px; padding-right: 5px">可签到</span>
                      </el-form-item>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="padding-bottom: 30px">
                  <el-col :span="8">
                    <el-form-item
                      label="放学时间"
                      :prop="'segments.' + index + '.endTime'"
                      :rules="[
                      { required: true, message: '放学时间不能为空', trigger: 'blur' },
                      { validator: (rule: any, value: string, callback: any) => checkEndTime(rule, value, callback, segment), trigger: 'blur' }
                    ]"
                    >
                      <el-time-picker v-model="segment.endTime" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item>
                      <el-form-item
                        :prop="'segments.' + index + '.signOutStart'"
                        :rules="[
                        { required: true, message: '签退开始时间不能为空', trigger: 'blur' },
                        { validator: (rule: any, value: string, callback: any) => checkSignOutStart(rule, value, callback, segment), trigger: 'blur' }
                      ]"
                      >
                        <el-time-picker v-model="segment.signOutStart" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                        <span style="padding-left: 5px; padding-right: 5px">至</span>
                      </el-form-item>
                      <el-form-item
                        :prop="'segments.' + index + '.signOutEnd'"
                        :rules="[
                        { required: true, message: '签退结束时间不能为空', trigger: 'blur' },
                        { validator: (rule: any, value: string, callback: any) => checkSignOutEnd(rule, value, callback, segment), trigger: 'blur' }
                      ]"
                      >
                        <el-time-picker v-model="segment.signOutEnd" format="HH:mm" value-format="HH:mm" style="width: 100px" />
                        <span style="padding-left: 5px; padding-right: 5px">可签退</span>
                      </el-form-item>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item prop="leaveEarlyMinutes">
          迟到<el-input-number
            v-model="form.comeLateMinutes"
            :controls="false"
            style="width: 80px; padding-left: 10px; padding-right: 10px"
          />分算正常
        </el-form-item>
        <el-form-item prop="leaveEarlyMinutes">
          早退<el-input-number
            v-model="form.leaveEarlyMinutes"
            :controls="false"
            style="width: 80px; padding-left: 10px; padding-right: 10px"
          />分算正常
        </el-form-item>
        <el-form-item prop="absenceMinutes">
          迟到<el-input-number v-model="form.absenceMinutes" :controls="false" style="width: 80px; padding-left: 10px; padding-right: 10px" />分算缺勤
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shift" lang="ts">
import { listShift, getShift, delShift, addShift, updateShift } from '@/api/attendance/setting/shift';
import { ShiftVO, ShiftQuery, ShiftForm } from '@/api/attendance/setting/shift/types';
import { TabsPaneContext } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { attendance_shift_type } = toRefs<any>(proxy?.useDict('attendance_shift_type'));

const shiftList = ref<ShiftVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const activeName = ref('1');
const queryFormRef = ref<ElFormInstance>();
const shiftFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShiftForm = {
  id: undefined,
  type: 1,
  shiftName: undefined,
  attendanceType: undefined,
  comeLateMinutes: undefined,
  leaveEarlyMinutes: undefined,
  absenceMinutes: undefined,
  remark: undefined,
  segments: []
};
const data = reactive<PageData<ShiftForm, ShiftQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: 1,
    shiftName: undefined,
    attendanceType: undefined,
    comeLateMinutes: undefined,
    leaveEarlyMinutes: undefined,
    absenceMinutes: undefined,
    params: {}
  },
  rules: {
    shiftName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    attendanceType: [{ required: true, message: '考勤类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const initSegment = {
  startTime: undefined,
  signInStart: undefined,
  signInEnd: undefined,
  endTime: undefined,
  signOutStart: undefined,
  signOutEnd: undefined
};

const initAttendanceShifts = [
  {
    label: '一天一次考勤',
    attendanceType: '1',
    segments: [{ ...initSegment }]
  },
  {
    label: '一天两次考勤',
    attendanceType: '2',
    segments: [{ ...initSegment }, { ...initSegment }]
  },
  {
    label: '一天三次考勤',
    attendanceType: '3',
    segments: [{ ...initSegment }, { ...initSegment }, { ...initSegment }]
  }
];

const copyInitAttendanceShifts = () => {
  return JSON.parse(JSON.stringify(initAttendanceShifts));
}

const attendanceShifts = ref(copyInitAttendanceShifts());

/** 查询考勤班次列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShift(queryParams.value);
  shiftList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  activeName.value = '1';
  attendanceShifts.value = copyInitAttendanceShifts();
  shiftFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ShiftVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleTabClick = (pane?: TabsPaneContext, event?: Event) => {
  const active = pane ? pane.props.name : activeName.value;
  const shifts = attendanceShifts.value.map((obj) => Object.assign({}, obj));
  form.value.segments = shifts.find((e) => e.attendanceType === active).segments;
};

const checkStartTime = (rule: any, value: string, callback: any, row: any) => {
  let flag = true;
  if (row.signInStart && value < row.signInStart) {
    flag = false;
    callback(new Error('上学时间不能小于签到开始时间'));
  }
  if (row.signInEnd && value > row.signInEnd) {
    flag = false;
    callback(new Error('上学时间不能大于签到结束时间'));
  }
  if (flag) {
    callback();
  }
};

const checkSignInStart = (rule: any, value: string, callback: any, row: any) => {
  let flag = true;
  if (row.startTime && row.startTime < value) {
    flag = false;
    callback(new Error('上学时间不能小于签到开始时间'));
  }
  if (row.signInEnd && row.signInEnd < value) {
    flag = false;
    callback(new Error('签到结束时间不能小于签到开始时间'));
  }
  if (flag) {
    callback();
  }
};

const checkSignInEnd = (rule: any, value: string, callback: any, row: any) => {
  let flag = true;
  if (row.startTime && row.startTime > value) {
    flag = false;
    callback(new Error('上学时间不能大于签到结束时间'));
  }
  if (row.signInStart && row.signInStart > value) {
    flag = false;
    callback(new Error('签到开始时间不能大于签到结束时间'));
  }
  if (flag) {
    callback();
  }
};

const checkEndTime = (rule: any, value: string, callback: any, row: any) => {
  if (row.signOutStart && value < row.signOutStart) {
    callback(new Error('放学时间不能小于签退开始时间'));
    return;
  }
  if (row.signOutEnd && value > row.signOutEnd) {
    callback(new Error('放学时间不能大于签退结束时间'));
  } else {
    callback();
  }
};

const checkSignOutStart = (rule: any, value: string, callback: any, row: any) => {
  if (row.endTime && row.endTime < value) {
    callback(new Error('放学时间不能小于签退开始时间'));
  } else if (row.signOutEnd && row.signOutEnd < value) {
    callback(new Error('签退结束时间不能小于签退开始时间'));
  } else {
    callback();
  }
};

const checkSignOutEnd = (rule: any, value: string, callback: any, row: any) => {
  if (row.endTime && row.endTime > value) {
    callback(new Error('放学时间不能大于签退结束时间'));
  } else if (row.signOutStart && row.signOutStart > value) {
    callback(new Error('签退开始时间不能大于签退结束时间'));
  } else {
    callback();
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  handleTabClick();
  dialog.visible = true;
  dialog.title = '添加考勤班次';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ShiftVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getShift(_id);
  Object.assign(form.value, res.data);
  activeName.value = form.value.attendanceType;
  const shifts = copyInitAttendanceShifts();
  shifts.forEach((e) => {
    if (e.attendanceType === activeName.value) {
      e.segments = form.value.segments;
    }
  });
  attendanceShifts.value = shifts;
  dialog.visible = true;
  dialog.title = '修改考勤班次';
};

/** 提交按钮 */
const submitForm = () => {
  shiftFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.attendanceType = activeName.value;
      // form.value.segments = attendanceShifts.value.find((e) => e.attendanceType === activeName.value)?.segments;
      if (form.value.id) {
        await updateShift(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addShift(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ShiftVO) => {
  const _ids = row ? [row.id] : ids.value;
  let msg = shiftList.value
    .filter((e) => _ids.find((id) => e.id === id))
    .map((e) => e.shiftName)
    .join(',');
  await proxy?.$modal.confirm('是否确认删除考勤班次名称为"' + msg + '"的数据项？').finally(() => (loading.value = false));
  await delShift(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/shift/export',
    {
      ...queryParams.value
    },
    `shift_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
